package com.easyexcle.demo.easyExcel.util;


import org.springframework.format.annotation.DateTimeFormat;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.IsoFields;
import java.util.*;

/**
 * @Author: lkz
 * @Title: WeeklyGrouping
 * @Description: 给定一个开始时间 计算时间段内的每一周  只显示周一至周五 可用
 * @Date: 2023/5/20 14:02
 */

public class WeeklyGrouping {

    public static Map<String, List<LocalDate>> groupByWeek(List<LocalDate> dates) {
        Map<String, List<LocalDate>> weeklyGroups = new LinkedHashMap<>();

        // 遍历每一个日期，将其加入对应的周分组中
        for (LocalDate date : dates) {
            int year = date.get(IsoFields.WEEK_BASED_YEAR);
            int weekOfYear = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
            List<LocalDate> weekDates = weeklyGroups.get(year+"_"+weekOfYear);
            if (weekDates == null) {
                weekDates = new ArrayList<>();
                weeklyGroups.put(year+"_"+weekOfYear, weekDates);
            }
            weekDates.add(date);
        }

        return weeklyGroups;
    }

    public static void main(String[] args) {

        // 定义开始时间和结束时间
        LocalDate start = LocalDate.of(2022, 10, 8);
        LocalDate end = LocalDate.of(2023, 11, 30);

        // 生成时间段内的周一到周五的日期
        List<LocalDate> weekdays = new ArrayList<>();
        long diffInDays = ChronoUnit.DAYS.between(start, end);
        for (int i = 0; i <= diffInDays; i++) {
            LocalDate date = start.plusDays(i);
            DayOfWeek dayOfWeek = date.getDayOfWeek();
//            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
//                weekdays.add(date);
//            }
            weekdays.add(date);

        }

        // 将日期按周分组，并输出结果
        Map<String, List<LocalDate>> weeklyGroups = groupByWeek(weekdays);
        for (Map.Entry<String, List<LocalDate>> entry : weeklyGroups.entrySet()) {
            String weekOfYear = entry.getKey();
            List<LocalDate> weekDates = entry.getValue();
            String[] split = weekOfYear.split("_");
            System.out.println(split[0]+"年"+"第 " + split[1] + " 周：");
            for (LocalDate date : weekDates) {
                System.out.println(date.toString());
            }
            System.out.println();
        }

    }


}
